package com.junqson.je.msg.controller;


import com.alibaba.fastjson.JSONObject;
import com.junqson.je.msg.util.SumUtil;
import lombok.extern.log4j.Log4j2;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Descriptions
 * @Company
 * @Author Junqson
 * @Date 2020/1/18 18:12
 * @Version 1.0
 */
@Log4j2
@RestController
public class SMSController {


    @Value("${sms.verifycode-template-code}")
    String TEMPLATEID;

    @Value("${sms.access-key-id}")
    String APP_KEY;

    @Value("${sms.access-secret}")
    String APP_SECRET;


    //发送验证码的请求路径URL
    private static final String
            SERVER_URL="https://api.netease.im/sms/sendcode.action";
    //网易云信分配的账号，请替换你在管理后台应用下申请的Appkey

    private static final String NONCE="686548";
    //短信模板ID
    private static final String MOBILE="15662756518";


    @RequestMapping("sendCode")
    public boolean sendVerifyCode(String phone,String code){
        HttpClient client = HttpClientBuilder.create().build();

        HttpPost httpPost = new HttpPost(SERVER_URL);

        String curTime = String.valueOf((new Date()).getTime() / 1000L);

        String checkSum = SumUtil.getCheckSum(APP_SECRET, code, curTime);

        // 设置请求的header
        httpPost.addHeader("AppKey", APP_KEY);
        httpPost.addHeader("Nonce", code);
        httpPost.addHeader("CurTime", curTime);
        httpPost.addHeader("CheckSum", checkSum);
        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");

        // 设置请求的的参数，requestBody参数
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();

        /*
         * 1.如果是模板短信，请注意参数mobile是有s的，详细参数配置请参考“发送模板短信文档”
         * 2.参数格式是jsonArray的格式，例如 "['13888888888','13666666666']"
         * 3.params是根据你模板里面有几个参数，那里面的参数也是jsonArray格式
         */
        nvps.add(new BasicNameValuePair("templateid", TEMPLATEID));
        nvps.add(new BasicNameValuePair("mobile", phone));
        nvps.add(new BasicNameValuePair("authCode", code));


        try {
            httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
            HttpResponse response = client.execute(httpPost);
            JSONObject JsonResult = JSONObject.parseObject(EntityUtils.toString(response.getEntity(), "utf-8"));

            if (JsonResult.getString("code").equals("200")){
                log.info("消息发送成功"+JsonResult.toString());
                return true;
            }else {
                return false;
            }
        } catch (UnsupportedEncodingException e) {
            log.warn("未支持的编码方式");
        } catch (ClientProtocolException e) {
            log.warn("客户端端口异常");
            e.printStackTrace();
        } catch (IOException e) {
            log.warn("io异常");
        }

        return false;
    }


    //    private static final String PRODUCT = "Dysmsapi";
//    private static final String DOMAIN = "dysmsapi.aliyuncs.com";
//    private static final String REGION_ID = "cn-hangzhou";
//    private static final String SIGN_NAME = "职易Jobease";
//    private static final String OK = "OK";


//    @Autowired
//    private IAcsClient client;
//
////    @RequestMapping("/sendCode")
////    public boolean sendVerifyCode(String phone, String code) {
////        SendSmsRequest request = new SendSmsRequest();
////        request.setSysMethod(MethodType.POST);
////        request.setPhoneNumbers(phone);
////        request.setSignName(SIGN_NAME);
////        request.setTemplateCode(vcTemplateCode);
////        request.setTemplateParam("{\"code\":\"" + code + "\"}");
////        try {
////            SendSmsResponse sendSmsResponse = client.getAcsResponse(request);
////            if (sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals(OK)) {
////                log.info("发送短信成功");
////                return true;
////            }
////            log.error(sendSmsResponse.getCode());
////        } catch (ClientException e) {
////            log.error("ClientException异常：" + e.getMessage());
//////            throw new MyException(ResultEnum.SEND_NOTE_ERROR);
////        }
////        log.error("发送短信失败");
////        return false;
////    }
//
//
//    public void sendMsg() {
//        CommonRequest request = new CommonRequest();
//        request.setSysMethod(MethodType.POST);
//        request.setSysDomain(DOMAIN);
//        request.setSysVersion("2017-05-25");
//        request.setSysAction("SendSms");
//        request.putQueryParameter("RegionId", REGION_ID);
//        request.putQueryParameter("TemplateCode", vcTemplateCode);
//
//        try {
//            CommonResponse response = client.getCommonResponse(request);
//            System.out.println(response.getData());
//        } catch (ServerException e) {
//            e.printStackTrace();
//        } catch (ClientException e) {
//            e.printStackTrace();
//        }
//    }
//
//    @Bean
//    public IAcsClient getClient() {
//        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessSecret);
//        IAcsClient client = new DefaultAcsClient(profile);
//        return client;
//    }


}
